package com.ygxsk.carhome.ui.park;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.gyf.immersionbar.ImmersionBar;
import com.kongzue.dialogx.dialogs.PopTip;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventParkingInside;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.ParkingLicenseBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.ParkNodeSectionAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2024/1/6  9:56
 * @Description:添加车辆管理列表页面
 */
public class ParkManageActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshlayoutinparking)
    SmartRefreshLayout refreshLayoutInParking;

    //该界面的列表主体
    @BindView(R.id.recyclerviewparking)
    RecyclerView recyClerViewParking;


    private List<BaseNode> mDataResources = new ArrayList<>();

    //多层适配器
    private ParkNodeSectionAdapter parkNodeSectionAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        //删除车牌监听
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_park_manage;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.fee_carplace_manager));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //2024年1月13日11:20:42 需求去掉右上角，节省一步。
        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutRight(true, 1, getResources().getString(R.string.parking_bundle_add_right), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                Bundle extra_bundle = new Bundle();
//                ActivityUtils.startActivity(extra_bundle, ParkingSelectSpaceActivity.class);
//
//            }
//        });


    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //设置方向
        recyClerViewParking.setLayoutManager(new MyLinearLayoutManager(this));

        parkNodeSectionAdapter = new ParkNodeSectionAdapter(ParkManageActivity.this);
        recyClerViewParking.setAdapter(parkNodeSectionAdapter);
        parkNodeSectionAdapter.setList(mDataResources);

        // TODO: 2024/1/6 11:07 去掉执行动画？
        recyClerViewParking.scheduleLayoutAnimation();
        parkNodeSectionAdapter.notifyDataSetChanged();

        refreshLayoutInParking.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (parkNodeSectionAdapter != null) {
                            parkNodeSectionAdapter.notifyDataSetChanged();
                        }

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {
            //是否有其他的执行逻辑？
            netWorkError();
        }

    }

    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.status, RepairStatusUpLoadType.STATE_HAS_DISPATCH.getIndex());//状态

//        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
//        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETAPPCARNOLISTFORREMOTE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getAPPCarNoListForRemote_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getAPPCarNoListForRemote(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(ParkManageActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<ParkingSpaceBean>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
//                        if (refreshLayoutInRepairManageListHistory != null) {
//                            refreshLayoutInRepairManageListHistory.setEnableLoadMore(true);
//                        }
                    }
                }).subscribe(new Consumer<ArrayList<ParkingSpaceBean>>() {
                    @Override
                    public void accept(ArrayList<ParkingSpaceBean> parkingSpaceBeanArrayList) throws Throwable {

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (parkingSpaceBeanArrayList != null && !parkingSpaceBeanArrayList.isEmpty()) {

                            for (ParkingSpaceBean parkingSpaceBean : parkingSpaceBeanArrayList) {

                                ArrayList<ParkingLicenseBean> parkingLicenseBeans = (ArrayList<ParkingLicenseBean>) parkingSpaceBean.getCarNoList();

                                if (parkingLicenseBeans != null && !parkingLicenseBeans.isEmpty()) {
                                    for (ParkingLicenseBean licenseBean : parkingLicenseBeans) {
                                        parkingSpaceBean.getChildNode().add(licenseBean);
                                    }
                                }

                                if (mDataResources != null) {
                                    mDataResources.add(parkingSpaceBean);
                                }

                            }

                        }

                        if (parkNodeSectionAdapter != null) {
                            parkNodeSectionAdapter.setList(mDataResources);
//                            parkNodeSectionAdapter.notifyDataSetChanged();
////                            parkNodeSectionAdapter.expandAll();
////                            parkNodeSectionAdapter.ex;
                        }


//                        if (repairManageItemOutSide != null) {
//                            ArrayList<RepairManageItemBean> currentDatas = repairManageItemOutSide.getDataList();
//                            if (currentDatas != null && !currentDatas.isEmpty()) {
//                                if (mDataResources != null) {
//                                    mDataResources.addAll(currentDatas);
//                                }
//                            }
//                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
//                        if (mDataResources != null && mDataResources.isEmpty()) {
//                            //同时禁用加载更多；
////                            if (refreshLayoutInRepairManageListHistory != null) {
////                                refreshLayoutInRepairManageListHistory.setEnableLoadMore(false);
////                            }
//
//                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
//                        }

//                        if (repairHistoryListAdapter != null) {
//                            repairHistoryListAdapter.notifyDataSetChanged();
//                        }

                        //给分页值
//                        pagination_upLoad = repairManageItemOutSide.getNextPagination();

                        //对列表改造：
//                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
//                            setFinishLoadMoreWithNoMoreData(refreshLayoutInParking, true);
//                        } else {
//                            setEnableLoadmore(refreshLayoutInParking, true);
//                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；
                        function_apiException(apiException);

                    }
                });

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.WHAT_GETAPPCARNOLISTFORREMOTE_URL: {

                if (mDataResources != null && mDataResources.isEmpty()) {

//                    if (refreshLayoutConsignFragment != null) {
//                        refreshLayoutConsignFragment.setEnableLoadMore(false);
//                    }

                    CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));
                }

                break;
            }

            default:
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadParkingOutSide(EventParkingInside eventParkingInside) {

        if (eventParkingInside != null) {

            if (eventParkingInside.getMessage() == ExtraValue.EVENTBUS_PARKING_OUTSIDE_ADD) {

                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (parkNodeSectionAdapter != null) {
                    parkNodeSectionAdapter.notifyDataSetChanged();
                }

                gainDatas();

            }

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadParkingInside(EventParkingInside eventParkingInside) {

        if (eventParkingInside != null) {

            if (eventParkingInside.getMessage() == ExtraValue.EVENTBUS_PARKINGINSIDE_DELETE) {

                if (materialDialog != null && materialDialog.isShowing()) {
                    materialDialog.dismiss();
                }

                View viewCard = View.inflate(mActivityInstance, R.layout.event_parking_inside, null);
                TextView textViewCard = viewCard.findViewById(R.id.textviewcardnumber);
                //textViewCard.setText(eventParkingInside.getCarNo() + ",将无法正常进入库！");

                SpanUtils.with(textViewCard)//
                        .append(eventParkingInside.getCarNo())//
                        .setBold()//
                        .setUnderline()//设置下划线//
                        .append(",未在库状态可删除！")//
                        .create();//

                //激发 弹窗弹出内容
                materialDialog = new MaterialDialog.Builder(ParkManageActivity.this)
                        .title("删除提示：")
                        //.content(StringUtils.getString(R.string.testtabhuh) + "您的车在离开车库后将会删除您的车牌！")
                        .customView(viewCard, false)
                        .contentColor(ColorUtils.getColor(R.color.buttonnomcolor))//
                        .positiveText("确定")
                        .positiveColor(ColorUtils.getColor(R.color.buttonnomcolor))
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                method_deleteById(eventParkingInside.getParkingSpaceIdOut(), eventParkingInside.getCarNoId());

                            }
                        }).onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                            }
                        }).canceledOnTouchOutside(false)
                        .show();

                //设置两个按钮内容
                materialDialog.getTitleView().setTextSize(16);//设置标题字体大小
                //materialDialogDelete.getContentView().setTextSize(14);//设置文本内容大小
                //materialDialogDelete.getContentView().setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

               /* SpanUtils.with(materialDialogDelete.getContentView())
                        .append(eventParkingInside.getCarNo()+",将无法正常进入库！")
                        //.setFontFamily()
                        //.setSpans()
                        .setBold()
                        .setUnderline()//设置下划线
                        //.setStrikethrough()
                        .append(StringUtils.getString(R.string.testtabhuh))
                        //.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD))
                        //.setBold()
                        .appendImage(R.drawable.)
                        .append("您的车在离开车库后将会删除您的车牌！").create();*/

                //2021-9-7 10:13:10 不要间距
                /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    materialDialogDelete.getContentView().setLetterSpacing(0.5f);
                }*/

                materialDialog.getActionButton(DialogAction.POSITIVE).setTextSize(15);
                materialDialog.getActionButton(DialogAction.NEGATIVE).setTextSize(15);


            }

        }

    }

    //删除车牌信息
    private void method_deleteById(String _parkingSpaceId, String _carNoId) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.parkingSpaceId, _parkingSpaceId);
        map.put(Parameterkey.carNoId, _carNoId);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_DELETECARNOFORREMOTE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.deleteCarNoForRemote_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .deleteCarNoForRemote(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(ParkManageActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
//                        CommUtils.checkMaterialDialog(materialDialog);
                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);
                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String valueString) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //删除成功
                        String serverMessage = getResources().getString(R.string.deletesucceepark);
                        PopTip.show(serverMessage).iconSuccess();

                        gainDatas();

                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException apiException) {
                        CommUtils.checkMaterialDialog(materialDialog);
                        //页面报错；
                        function_apiException(apiException);
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

//        if (materialDialogDelete != null) {
//            if (materialDialogDelete.isShowing()) {
//                materialDialogDelete.dismiss();
//            }
//            materialDialogDelete = null;
//        }

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
            mDataResources = null;
        }

        if (parkNodeSectionAdapter != null) {
            parkNodeSectionAdapter.notifyDataSetChanged();
            parkNodeSectionAdapter = null;
        }


        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    public void processExtraData() {

        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {
            //jumpFromFlag = bundle.getInt(ConstantApi.EXTRA_JUMPFROM_WHERE);
        }

    }
}